<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="产品名称" prop="productName">
        <el-input
            v-model="queryParams.productName"
            placeholder="请输入产品名称"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品编码" prop="code">
        <el-input
            v-model="queryParams.code"
            placeholder="请输入产品编码"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="批次号" prop="batchNumber">
        <el-input
            v-model="queryParams.batchNumber"
            placeholder="请输入批次号"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['md:main:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['md:main:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['md:main:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['md:main:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            icon="el-icon-download"
            size="mini"
            :disabled="multiple"
            @click="handleDownloadBatchQrCodes"
            v-hasPermi="['md:main:downloadQr']"
        >批量下载二维码</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="el-icon-time"
            size="mini"
            @click="showDownloadTasks"
            v-hasPermi="['md:main:downloadQr']"
        >下载任务</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="mainList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="产品编码" align="center" prop="code" />
      <el-table-column label="产品属性" align="center" prop="attributes" />
      <el-table-column label="规格" align="center" prop="specification" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="批次号" align="center" prop="batchNumber" />
      <el-table-column label="批次数量" align="center" prop="quantity" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['md:main:edit']"
          >修改</el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['md:main:remove']"
          >删除</el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-tickets"
              @click="handleGenerateQrRow(scope.row)"
              v-hasPermi="['md:main:generateQr']"
          >生成二维码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改溯源码主对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="产品信息">
          <el-button @click="openItemSelector" type="primary" size="minor">选择物料</el-button>
        </el-form-item>

        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入产品名称" readonly />
        </el-form-item>
        <el-form-item label="产品编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入产品编码" readonly />
        </el-form-item>
        <el-form-item label="产品属性" prop="attributes">
          <el-input v-model="form.attributes" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="规格" prop="specification">
          <el-input v-model="form.specification" placeholder="请输入规格" readonly />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位" readonly />
        </el-form-item>
        <el-form-item label="配料表" prop="ingredients">
          <el-input v-model="form.ingredients" placeholder="请输入配料表" />
        </el-form-item>
        <el-form-item label="保质期" prop="shelfLife">
          <el-date-picker
              v-model="form.shelfLife"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择保质期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="批次号" prop="batchNumber">
          <el-input v-model="form.batchNumber" placeholder="请输入批次号" />
        </el-form-item>
        <el-form-item label="批次数量" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入批次数量" />
        </el-form-item>

        <el-form-item label="产品图片">
          <el-upload
              class="avatar-uploader"
              :show-file-list="true"
              :on-success="handleProductImageSuccess"
              :before-upload="beforeUpload"
              :http-request="customProductUpload"
              :on-error="handleProductImageError"
              :action="'javascript:void(0)'"
              accept="image/*"
              multiple
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过5MB</div>
          </el-upload>

          <!-- 产品图片预览区域 -->
          <div v-if="form.productImageUrls && form.productImageUrls.length > 0" style="margin-top: 10px;">
            <div v-for="(url, index) in form.productImageUrls" :key="generateKey(index)" style="display: inline-block; margin-right: 10px; position: relative;">
              <img :src="url" alt="产品图片" style="max-width: 150px; max-height: 150px;" />
              <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  circle style="position: absolute; top: 5px; right: 5px;"
                  @click.stop="deleteProductImage(index)"
              ></el-button>
            </div>
          </div>
        </el-form-item>


        <!-- 凭证上传 -->
        <el-form-item label="凭证上传">
          <el-upload
              class="avatar-uploader"
              :show-file-list="true"
              :on-success="handleCertificateSuccess"
              :before-upload="beforeUpload"
              :http-request="customCertificateUpload"
              :on-error="handleCertificateError"
              :action="'javascript:void(0)'"
              accept="image/*"
              multiple
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过5MB</div>
          </el-upload>
        </el-form-item>

        <!-- 凭证图片预览区域 -->
        <div v-if="form.imageUrls && form.imageUrls.length > 0" style="margin-top: 10px;">
          <div v-for="(url, index) in form.imageUrls" :key="generateKey(index)" style="display: inline-block; margin-right: 10px; position: relative;">
            <img :src="url" alt="凭证图片" style="max-width: 150px; max-height: 150px;" />
            <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                circle style="position: absolute; top: 5px; right: 5px;"
                @click.stop="deleteCertificateImage(index)"
            ></el-button>
          </div>
        </div>

        <!-- 进口关单上传 -->
        <el-form-item label="进口关单">
          <el-upload
              class="avatar-uploader"
              :show-file-list="true"
              :on-success="handleImportCustomsBillSuccess"
              :before-upload="beforeUpload"
              :http-request="customImportCustomsBillUpload"
              :on-error="handleImportCustomsBillError"
              :action="'javascript:void(0)'"
              accept="image/*"
              multiple
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过5MB</div>
          </el-upload>
        </el-form-item>

        <!-- 进口关单图片预览区域 -->
        <div v-if="form.importCustomsBills && form.importCustomsBills.length > 0" style="margin-top: 10px;">
          <div v-for="(url, index) in form.importCustomsBills" :key="generateKey(index)" style="display: inline-block; margin-right: 10px; position: relative;">
            <img :src="url" alt="进口关单" style="max-width: 150px; max-height: 150px;" />
            <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                circle style="position: absolute; top: 5px; right: 5px;"
                @click.stop="deleteImportCustomsBillImage(index)"
            ></el-button>
          </div>
        </div>



      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 物料选择弹窗 -->
    <el-dialog title="选择物料" :visible.sync="showItemDialog" width="70%">
      <!-- 搜索表单 -->
      <el-form :inline="true" size="small" @submit.native.prevent="handleItemQuery">
        <el-form-item label="物料名称">
          <el-input v-model="itemQueryParams.itemName" placeholder="请输入物料名称" clearable @clear="handleItemQuery" />
        </el-form-item>
        <el-form-item label="物料编码">
          <el-input v-model="itemQueryParams.itemCode" placeholder="请输入物料编码" clearable @clear="handleItemQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" native-type="submit">搜索</el-button>
          <el-button @click="resetItemQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table :data="itemList" @row-click="selectItemRow" highlight-current-row border>
        <el-table-column prop="itemName" label="物料名称" />
        <el-table-column prop="itemCode" label="物料编码" />
        <el-table-column prop="specification" label="规格" />
        <el-table-column prop="unitOfMeasure" label="单位" />
        <el-table-column prop="mkItemAttr" label="属性" />
      </el-table>

      <!-- 分页组件 -->
      <pagination
          v-show="itemTotal > 0"
          :total="itemTotal"
          :page.sync="itemQueryParams.pageNum"
          :limit.sync="itemQueryParams.pageSize"
          @pagination="loadItemList"
      />

      <!-- 弹窗底部按钮 -->
      <div slot="footer">
        <el-button @click="showItemDialog = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 下载任务管理对话框 -->
    <el-dialog title="下载任务管理" :visible.sync="showTaskDialog" width="60%">
      <el-table :data="downloadTasksArray" style="width: 100%">
        <el-table-column prop="batchNumber" label="批次号" width="150"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getTaskStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="progress" label="进度" width="120">
          <template slot-scope="scope">
            <el-progress
              :percentage="scope.row.progress"
              :status="scope.row.status === 'COMPLETED' ? 'success' : scope.row.status === 'FAILED' ? 'exception' : ''">
            </el-progress>
          </template>
        </el-table-column>
        <el-table-column prop="message" label="消息"></el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.status === 'COMPLETED'"
              size="mini"
              type="primary"
              @click="downloadCompletedTaskFile(scope.row.taskId)"
            >下载</el-button>
            <el-button
              v-if="scope.row.status === 'PROCESSING' || scope.row.status === 'CREATED'"
              size="mini"
              type="danger"
              @click="cancelDownloadTask(scope.row.taskId)"
            >取消</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer">
        <el-button @click="refreshTaskList">刷新</el-button>
        <el-button @click="showTaskDialog = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listMain,
  getMain,
  delMain,
  addMain,
  updateMain,
  generateQrCodes,
  uploadImage,
  downloadBatchQrCodes,
  // 异步下载相关API
  downloadBatchQrCodesAsync,
  getDownloadTaskStatus,
  cancelDownloadTask,
  downloadTaskFile
} from "@/api/mes/qr/main";
import { listMdItem } from "@/api/mes/md/mdItem";

export default {
  name: "Main",
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      mainList: [],
      title: "",
      open: false,
      showQrDialog: false,
      qrSubDetailList: [],
      showItemDialog: false,
      itemList: [],
      itemTotal: 0,
      selectedBatchInfo: [],
      itemQueryParams: {
        pageNum: 1,
        pageSize: 10,
        itemName: null,
        itemCode: null
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: null,
        code: null,
        batchNumber: null
      },
      form: {
        id: null,
        productName: null,
        code: null,
        attributes: null,
        specification: null,
        unit: null,
        batchNumber: null,
        quantity: null,
        imageUrls: [],
        productImageUrls: [],
        importCustomsBills: []
      },
      // 用于强制更新key的计数器
      updateKey: 0,
      rules: {
        productName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" }
        ],
        code: [
          { required: true, message: "产品编码不能为空", trigger: "blur" }
        ]
      },
      // 异步下载任务相关
      showTaskDialog: false,
      downloadTasks: new Map(), // 存储下载任务
      taskPollingTimers: new Map(), // 存储轮询定时器
      taskRefreshTimer: null // 任务列表刷新定时器
    };
  },
  computed: {
    // 将Map转换为数组以便在表格中显示
    downloadTasksArray() {
      return Array.from(this.downloadTasks.values());
    }
  },
  created() {
    this.getList();
  },
  beforeDestroy() {
    // 清理所有定时器
    this.cleanupTimers();
  },
  methods: {
    getList() {
      this.loading = true;
      listMain(this.queryParams).then(response => {
        this.mainList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    showQrDetails(qrList) {
      this.qrSubDetailList = qrList;
      this.showQrDialog = true;
    },
    reset() {
      this.form = {
        id: null,
        productName: null,
        code: null,
        attributes: null,
        specification: null,
        unit: null,
        batchNumber: null,
        quantity: null,
        imageUrls: [],
        productImageUrls: [],
        ingredients: undefined,
        shelfLife: undefined,
        importCustomsBills: []
      };
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.resetFields();
        }
      });
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleAdd() {
      console.log("点击新增按钮");
      this.reset();
      this.open = true;
      this.title = "添加溯源码主";
    },
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getMain(id).then(response => {
        this.form = { ...response.data };

        // 凭证图 - 处理修改时的完整URL
        if (response.data.imageUrl && !Array.isArray(response.data.imageUrl)) {
          this.form.imageUrls = response.data.imageUrl.split(',').filter(Boolean);
        } else {
          this.form.imageUrls = [];
        }

        // 产品图 - 处理修改时的完整URL
        if (response.data.productImageUrl && !Array.isArray(response.data.productImageUrl)) {
          this.form.productImageUrls = response.data.productImageUrl.split(',').filter(Boolean);
        } else {
          this.form.productImageUrls = [];
        }

        // 进口关单图 - 处理修改时的完整URL
        if (response.data.importCustomsBill && !Array.isArray(response.data.importCustomsBill)) {
          this.form.importCustomsBills = response.data.importCustomsBill.split(',').filter(Boolean);
        } else {
          this.form.importCustomsBills = [];
        }

        // 保存原始图片数据，用于对比删除
        this.form.originalImageUrls = [...this.form.imageUrls];
        this.form.originalProductImageUrls = [...this.form.productImageUrls];
        this.form.originalImportCustomsBills = [...this.form.importCustomsBills];

        this.open = true;
        this.title = "修改溯源码主";
      });
    },
    // 提交表单时正确处理图片路径
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 处理凭证图 - 只提交当前存在的图片
          this.form.imageUrl = this.form.imageUrls.join(',');

          // 处理产品图
          this.form.productImageUrl = this.form.productImageUrls.join(',');

          // 处理进口关单图
          this.form.importCustomsBill = this.form.importCustomsBills.join(',');

          if (!this.form.id) {
            addMain(this.form).then(res => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          } else {
            updateMain(this.form).then(() => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 上传前校验
    beforeUpload(file) {
      const isValidType = ['image/jpeg', 'image/png'].includes(file.type);
      const isValidSize = file.size / 1024 / 1024 < 5;
      if (!isValidType) {
        this.$message.error("只能上传 JPG/PNG 格式的图片");
        return false;
      }
      if (!isValidSize) {
        this.$message.error("图片大小不能超过 5MB");
        return false;
      }
      return true;
    },

    // 生成唯一的key用于强制更新DOM
    generateKey(index) {
      return `${index}_${this.updateKey}`;
    },

    // ==================== 产品图片上传逻辑 ====================
    // 自定义产品图片上传
    customProductUpload({ file }) {
      const formData = new FormData();
      formData.append("file", file);
      return uploadImage(formData);
    },

    // 产品图片上传成功处理
    handleProductImageSuccess(response, file) {
      this.handleUploadSuccess('productImageUrls', response);
    },

    // 产品图片上传失败处理
    handleProductImageError(error) {
      this.$message.error("产品图片上传出错：" + error.message);
    },

    // 删除产品图片
    deleteProductImage(index) {
      this.$confirm('确定要删除这张产品图片吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 使用filter创建新数组
        const newUrls = this.form.productImageUrls.filter((item, i) => i !== index);
        // 更新数组
        this.form.productImageUrls = newUrls;
        // 更新表单中的productImageUrl字段，确保在提交时能正确更新数据库
        this.form.productImageUrl = newUrls.join(',');
        // 增加updateKey强制更新DOM
        this.updateKey++;
        this.$message.success('删除成功');
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },

    // ==================== 凭证图片上传逻辑 ====================
    // 自定义凭证图片上传
    customCertificateUpload({ file }) {
      const formData = new FormData();
      formData.append("file", file);
      return uploadImage(formData);
    },

    // 凭证图片上传成功处理
    handleCertificateSuccess(response, file) {
      this.handleUploadSuccess('imageUrls', response);
    },

    // 凭证图片上传失败处理
    handleCertificateError(error) {
      this.$message.error("凭证图片上传出错：" + error.message);
    },

    // 删除凭证图片
    deleteCertificateImage(index) {
      this.$confirm('确定要删除这张凭证图片吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 使用filter创建新数组
        const newUrls = this.form.imageUrls.filter((item, i) => i !== index);
        // 更新数组
        this.form.imageUrls = newUrls;
        // 更新表单中的imageUrl字段，确保在提交时能正确更新数据库
        this.form.imageUrl = newUrls.join(',');
        // 增加updateKey强制更新DOM
        this.updateKey++;
        this.$message.success('删除成功');
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },

    // ==================== 进口关单上传逻辑 ====================
    // 自定义进口关单上传
    customImportCustomsBillUpload({ file }) {
      const formData = new FormData();
      formData.append("file", file);
      return uploadImage(formData);
    },

    // 进口关单上传成功处理
    handleImportCustomsBillSuccess(response, file) {
      this.handleUploadSuccess('importCustomsBills', response);
    },

    // 进口关单上传失败处理
    handleImportCustomsBillError(error) {
      this.$message.error("进口关单上传出错：" + error.message);
    },

    // 删除进口关单图片
    deleteImportCustomsBillImage(index) {
      this.$confirm('确定要删除这张进口关单图片吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 使用filter创建新数组
        const newUrls = this.form.importCustomsBills.filter((item, i) => i !== index);
        // 更新数组
        this.form.importCustomsBills = newUrls;
        // 更新表单中的importCustomsBill字段，确保在提交时能正确更新数据库
        this.form.importCustomsBill = newUrls.join(',');
        // 增加updateKey强制更新DOM
        this.updateKey++;
        this.$message.success('删除成功');
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },

    // ==================== 通用上传处理函数 ====================
    // 通用上传成功处理函数
    handleUploadSuccess(field, response) {
      if (response.code === 200 && response.data) {
        const baseUrl = process.env.VUE_APP_BASE_API;
        let newUrls = [];

        if (typeof response.data === 'string') {
          newUrls.push(baseUrl + response.data);
        } else if (Array.isArray(response.data)) {
          newUrls = response.data.map(path => baseUrl + path);
        } else if (typeof response.data === 'object' && response.data.url) {
          newUrls.push(baseUrl + response.data.url);
        } else {
          this.$message.error("图片路径格式不支持");
          return;
        }

        this.form[field] = [...this.form[field], ...newUrls];
        this.$message.success("上传成功");
      } else {
        this.$message.error("上传失败");
      }
    },
    handleGenerateQrRow(row) {
      if (!row.batchNumber || !row.quantity || !row.id) {
        this.$modal.msgError("数据不完整");
        return;
      }
      generateQrCodes(row.batchNumber, row.quantity, row.id).then(res => {
        this.$modal.msgSuccess(`成功生成 ${res.length} 个二维码`);
        this.showQrDetails(res);
      }).catch(() => {
        this.$modal.msgError("生成二维码失败");
      });
    },

    selectItemRow(row) {
      this.form.productName = row.itemName;
      this.form.code = row.itemCode;
      this.form.attributes = row.mkItemAttr;
      this.form.specification = row.specification;
      this.form.unit = row.unitOfMeasure;
      this.showItemDialog = false;
    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除溯源码主编号为"' + ids + '"的数据项？').then(() => {
        return delMain(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleExport() {
      this.download('md/main/export', {
        ...this.queryParams
      }, `main_${new Date().getTime()}.xlsx`)
    },
    // 打开物料弹窗并加载默认数据
    openItemSelector() {
      this.showItemDialog = true;
      this.loadItemList();
      this.$nextTick(() => {
        this.loadItemList();
      });
    },

    // 加载物料列表
    loadItemList() {
      listMdItem(this.itemQueryParams).then(res => {
        this.itemList = res.rows;
        this.itemTotal = res.total;
      });
    },

    // 触发搜索
    handleItemQuery() {
      this.itemQueryParams.pageNum = 1;
      this.loadItemList();
    },

    // 重置搜索条件
    resetItemQuery() {
      this.itemQueryParams = {
        pageNum: 1,
        pageSize: 10,
        itemName: null,
        itemCode: null
      };
      this.loadItemList();
    },

    // 行点击事件
    selectItemRow(row) {
      this.form.productName = row.itemName;
      this.form.code = row.itemCode;
      this.form.attributes = row.mkItemAttr;
      this.form.specification = row.specification;
      this.form.unit = row.unitOfMeasure;
      this.showItemDialog = false;
    },
    // 多选框选中数据 - 需要扩展以存储批次信息
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length

      // 存储选中行的批次信息
      this.selectedBatchInfo = selection.map(item => ({
        mainId: item.id,  // 注意这里是主表ID
        batchNumber: item.batchNumber
      }));
    },
    /**
     * 批量下载二维码（同步方式）
     */
    handleDownloadBatchQrCodes() {
      // 检查是否有选中行
      if (this.ids.length === 0) {
        this.$modal.msgWarning("请至少选择一条数据进行下载");
        return;
      }

      // 检查选中行是否都有批次号和主表ID
      const invalidRows = this.selectedBatchInfo.filter(item => !item.batchNumber || !item.mainId);
      if (invalidRows.length > 0) {
        this.$modal.msgWarning("部分选中数据缺少批次号或主表ID");
        return;
      }

      // 询问用户选择下载方式
      this.$confirm('选择下载方式：确定使用同步下载（适合小批量），取消使用异步下载（适合大批量）', '下载方式选择', {
        confirmButtonText: '同步下载',
        cancelButtonText: '异步下载',
        type: 'warning'
      }).then(() => {
        // 同步下载
        this.syncDownloadBatchQrCodes();
      }).catch(() => {
        // 异步下载
        this.asyncDownloadBatchQrCodes();
      });
    },

    /**
     * 同步下载二维码
     */
    syncDownloadBatchQrCodes() {
      // 按批次号分组下载
      const batchGroups = {};
      this.selectedBatchInfo.forEach(item => {
        if (!batchGroups[item.batchNumber]) {
          batchGroups[item.batchNumber] = item.mainId;
        }
      });

      this.$modal.confirm('是否确认批量下载选中的 ' + Object.keys(batchGroups).length + ' 个批次的二维码？').then(() => {
        // 依次下载每个批次
        Object.keys(batchGroups).forEach((batchNumber, index) => {
          setTimeout(() => {
            this.downloadSingleBatch({
              mainId: batchGroups[batchNumber],
              batchNumber: batchNumber
            });
          }, index * 1000);
        });

        this.$modal.msgSuccess("开始批量下载，请稍候...");
      }).catch(() => {});
    },

    /**
     * 异步下载二维码
     */
    async asyncDownloadBatchQrCodes() {
      // 检查是否有选中行
      if (this.ids.length === 0) {
        this.$modal.msgWarning("请至少选择一条数据进行下载");
        return;
      }

      // 检查选中行是否都有批次号和主表ID
      const invalidRows = this.selectedBatchInfo.filter(item => !item.batchNumber || !item.mainId);
      if (invalidRows.length > 0) {
        this.$modal.msgWarning("部分选中数据缺少批次号或主表ID");
        return;
      }

      // 按批次号分组下载
      const batchGroups = {};
      this.selectedBatchInfo.forEach(item => {
        if (!batchGroups[item.batchNumber]) {
          batchGroups[item.batchNumber] = item.mainId;
        }
      });

      this.$modal.confirm('是否确认异步下载选中的 ' + Object.keys(batchGroups).length + ' 个批次的二维码？').then(async () => {
        // 依次提交每个批次的下载任务
        for (const batchNumber of Object.keys(batchGroups)) {
          const mainId = batchGroups[batchNumber];
          await this.submitDownloadTask(batchNumber, mainId);
        }

        this.$modal.msgSuccess("下载任务已提交，请在任务管理中查看进度");
        // 移除了自动打开任务管理对话框的代码: this.showDownloadTasks();
      }).catch(() => {});
    },


    /**
     * 下载单个批次的二维码（同步）
     */
    downloadSingleBatch(batchInfo) {
      const downloadData = {
        mainId: batchInfo.mainId,
        batchNumber: batchInfo.batchNumber
      };

      downloadBatchQrCodes(downloadData).then(response => {
        // 创建下载链接
        const blob = new Blob([response]);
        const fileName = batchInfo.batchNumber + '_二维码.zip';

        // 创建并触发下载
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
        window.URL.revokeObjectURL(link.href);

        this.$modal.msgSuccess("批次 " + batchInfo.batchNumber + " 二维码下载成功");
      }).catch(error => {
        this.$modal.msgError("批次 " + batchInfo.batchNumber + " 下载失败，请重试");
        console.error("下载失败:", error);
      });
    },

    /**
     * 提交异步下载任务
     */
    async submitDownloadTask(batchNumber, mainId) {
      try {
        const downloadData = {
          mainId: mainId,
          batchNumber: batchNumber
        };

        const response = await downloadBatchQrCodesAsync(downloadData);
        if (response.code === 200) {
          const taskId = response.data;
          // 创建任务对象
          const task = {
            taskId: taskId,
            batchNumber: batchNumber,
            status: 'CREATED',
            progress: 0,
            message: '任务已提交'
          };

          // 存储任务
          this.downloadTasks.set(taskId, task);

          // 开始轮询任务状态
          this.startPollingTaskStatus(taskId);

          this.$modal.msgSuccess(`批次 ${batchNumber} 的下载任务已提交`);
        } else {
          this.$modal.msgError(`提交批次 ${batchNumber} 的下载任务失败: ${response.msg}`);
        }
      } catch (error) {
        this.$modal.msgError(`提交批次 ${batchNumber} 的下载任务失败: ${error.message}`);
      }
    },

    /**
         * 轮询任务状态
         */
        startPollingTaskStatus(taskId) {
          // 如果已有轮询定时器，先清除
          if (this.taskPollingTimers.has(taskId)) {
            clearInterval(this.taskPollingTimers.get(taskId));
          }

          const timer = setInterval(async () => {
            try {
              const response = await getDownloadTaskStatus(taskId);
              if (response.code === 200) {
                const taskStatus = response.data;
                const task = this.downloadTasks.get(taskId);
                if (task) {
                  task.status = taskStatus.status;
                  task.progress = taskStatus.progress;
                  task.message = taskStatus.message;

                  // 如果任务完成，自动触发下载
                  if (taskStatus.status === 'COMPLETED') {
                    clearInterval(this.taskPollingTimers.get(taskId));
                    this.taskPollingTimers.delete(taskId);
                    // 自动下载完成的文件
                    this.downloadCompletedTaskFile(taskId);
                  } else if (taskStatus.status === 'FAILED' || taskStatus.status === 'CANCELLED') {
                    clearInterval(this.taskPollingTimers.get(taskId));
                    this.taskPollingTimers.delete(taskId);
                  }
                }
              }
            } catch (error) {
              console.error("轮询任务状态失败:", error);
            }
          }, 2000); // 每2秒轮询一次

          this.taskPollingTimers.set(taskId, timer);
        },

    /**
         * 下载完成的任务文件
         */
        async downloadCompletedTaskFile(taskId) {
          try {
            const task = this.downloadTasks.get(taskId);
            if (!task) {
              this.$modal.msgError("任务不存在");
              return;
            }

            // 使用request下载文件
            const response = await downloadTaskFile(taskId);

            // 创建下载链接
            const blob = new Blob([response]);
            const fileName = task.batchNumber + '_二维码.zip';

            // 创建并触发下载
            const link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = fileName;
            link.style.display = 'none';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            window.URL.revokeObjectURL(link.href);

            this.$modal.msgSuccess("文件下载开始");
          } catch (error) {
            this.$modal.msgError("下载文件失败: " + error.message);
          }
        },

    /**
     * 取消下载任务
     */
    async cancelDownloadTask(taskId) {
      try {
        const response = await cancelDownloadTask(taskId);
        if (response.code === 200) {
          const task = this.downloadTasks.get(taskId);
          if (task) {
            task.status = 'CANCELLED';
            task.message = '任务已取消';
          }
          this.$modal.msgSuccess("任务已取消");
        } else {
          this.$modal.msgError("取消任务失败: " + response.msg);
        }
      } catch (error) {
        this.$modal.msgError("取消任务失败: " + error.message);
      }
    },

    /**
     * 显示下载任务管理对话框
     */
    showDownloadTasks() {
      this.showTaskDialog = true;
      this.refreshTaskList();
    },

    /**
     * 刷新任务列表
     */
    refreshTaskList() {
      // 这里可以添加手动刷新逻辑，目前任务状态通过轮询自动更新
    },

    /**
     * 获取任务状态的标签类型
     */
    getTaskStatusType(status) {
      switch (status) {
        case 'CREATED':
          return '';
        case 'PROCESSING':
          return 'warning';
        case 'COMPLETED':
          return 'success';
        case 'FAILED':
          return 'danger';
        case 'CANCELLED':
          return 'info';
        default:
          return '';
      }
    },

    /**
     * 清理所有定时器
     */
    cleanupTimers() {
      // 清理轮询定时器
      for (const timer of this.taskPollingTimers.values()) {
        clearInterval(timer);
      }
      this.taskPollingTimers.clear();

      // 清理刷新定时器
      if (this.taskRefreshTimer) {
        clearInterval(this.taskRefreshTimer);
        this.taskRefreshTimer = null;
      }
    }
  }
};
</script>
